package com.weirong.smartvault.dao.util;

import com.weirong.smartvault.entity.Authority;
import org.springframework.data.jpa.domain.Specification;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

public class MultiQueryAuthorityRepositoryUtil {

    public static Specification<Authority> where(String remark, Integer parentId, Integer grade)
    {
        return new Specification<Authority>() {
            @Override
            public Predicate toPredicate(Root<Authority> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<Predicate>();
                if (remark != null && !remark.trim().equals("")) predicates.add(criteriaBuilder.equal(root.<String>get("remark"), remark));
                if (parentId != null) predicates.add(criteriaBuilder.equal(root.<Integer>get("parentId"), parentId));
                if (grade != null) predicates.add(criteriaBuilder.equal(root.<String>get("grade"), grade));
                return criteriaQuery.where(predicates.toArray(new Predicate[predicates.size()])).getRestriction();
            }
        };
    }

}